//
//  GYMineVC.m
//  GYDemo
//
//  Created by mac on 2018/3/22.
//  Copyright © 2018年 mac. All rights reserved.
//

//
//                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
//            __.'              ~.   .~              `.__
//          .'//                  \./                  \\`.
//        .'//                     |                     \\`.
//      .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-. \\`.
//    .'//.-"                 `-.  |  .-'                 "-.\\`.
//  .'//______.============-..   \ | /   ..-============.______\\`.
//.'______________________________\|/______________________________`.
//
//

#import "GYMineVC.h"
#import "Head.h"
#import "GYMineHeadView.h"
#import "GYStorageUserViewModel.h"
#import "GYLoginViewModel.h"
@interface GYMineVC ()
@property (nonatomic,strong) GYUserViewModel *userViewModel;
@property (nonatomic,strong) GYLoginViewModel *LoginViewModel;
@property (nonatomic,strong) GYStorageUserViewModel *StorageUserViewModel;
@property (nonatomic, strong) UIView *headBGView;
@property (nonatomic, strong) GYMineHeadView *headView;
@property (nonatomic,strong) NSArray *needAuths;
@end

@implementation GYMineVC
#pragma mark - getter and setter
-(GYLoginViewModel *)LoginViewModel
{
    if (!_LoginViewModel) {
        _LoginViewModel=[GYLoginViewModel shareInterface];
    }
    return _LoginViewModel;
}
-(GYUserViewModel *)userViewModel
{
    if (!_userViewModel) {
        _userViewModel = [GYUserViewModel shareInterface];
    }
    return _userViewModel;
}
-(UIView *)headBGView
{
    if (!_headBGView) {
        _headBGView = [UIView new];
        _headBGView.width = self.view.width;
        _headBGView.height = self.topShelterHeight;
        _headBGView.backgroundColor = Main_Color_Red;
    }
    return _headBGView;
}
-(GYStorageUserViewModel *)StorageUserViewModel
{
    if (!_StorageUserViewModel) {
        _StorageUserViewModel=[GYStorageUserViewModel shareInterface];
    }
    return _StorageUserViewModel;
}
-(UIView *)headView
{
    if (!_headView) {
        _headView = [[GYMineHeadView alloc] init];
        _headView.frame = CGRectMake(0, 0, self.view.width, WFCGFloatY(60));
        _headView.width = self.view.width;
        _headView.height = WFCGFloatY(60);
        _headView.userInteractionEnabled = YES;
        _headView.backgroundColor = Main_Color_Red;
        [_headView setCallback:^{
            if (![GYLoginViewModel shareInterface].loginstatus) {
                [[GCPresenter shareInterface]loadLogin];
            }
            
        }];
    }
    return _headView;
}
-(NSArray *)needAuths
{
    if (!_needAuths) {
        _needAuths = @[@"buyInfo",@"buyOrderInfo",@"companyInfo",@"productInfo",@"saleRecordInfo",@"saleOrderInfo",@"LogisticShopInfo",@"StorageAuth",@"LogisticsAuth"];
    }
    return _needAuths;
}
#pragma mark - event
#pragma mark - method
-(void)initilization
{
    self.navigationItem.title = @"会员中心";
    self.extendedLayoutIncludesOpaqueBars = YES;
    
    if (@available(iOS 11.0, *)) {
        self.baseTable.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.baseTable.contentInset = UIEdgeInsetsMake([self topShelterHeight], 0, [self bottomShelterHeight], 0);
    self.view.backgroundColor = Main_Color_BG;
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    self.isGroup = YES;
    [self.view addSubview:self.headBGView];
    [self.view addSubview:self.baseTable];
    [self.baseTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.baseTable setSeparatorColor: Main_Color_BG];
    [self.baseTable setBackgroundColor:[UIColor clearColor]];
    [self.baseTable setTintColor:Main_Color_BG];
    self.baseTable.scrollIndicatorInsets = self.baseTable.contentInset;
    [self.baseTable setTableHeaderView:self.headView];
    
    [self viewModelBand];
    
    //第二种样式
    _laytoutType = 1;
    
    @WeakSelf;
    self.baseTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [selfp reloadData];
        [selfp.baseTable.mj_header endRefreshing];
    }];
    ((MJRefreshNormalHeader *)self.baseTable.mj_header).activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    ((MJRefreshNormalHeader *)self.baseTable.mj_header).stateLabel.hidden = YES;
    ((MJRefreshNormalHeader *)self.baseTable.mj_header).lastUpdatedTimeLabel.hidden = YES;
    [[self.baseTable.mj_header valueForKey:@"loadingView"] setCenterX:self.view.centerX];
    ((UIImageView *)[self.baseTable.mj_header valueForKey:@"arrowView"]).image = [((UIImageView *)[self.baseTable.mj_header valueForKey:@"arrowView"]).image rt_lightenWithLevel:1];
    //[self.baseTable.mj_header beginRefreshing];
}
-(void)viewModelBand
{
    @WeakSelf;
    GCBaseObservationModel *observation = [GCBaseObservationModel new];
    observation.observation = self.userViewModel;
    observation.keyPath = @"userModel";
    observation.handler = ^(NSString *keyPath) {
        [selfp reloadView];
    };
    
    
    GCBaseObservationModel *storageObservation = [GCBaseObservationModel new];
    storageObservation.observation = self.StorageUserViewModel;
    storageObservation.keyPath = @"storageUserInfoModel";
    storageObservation.handler = ^(NSString *keyPath) {
        [selfp reloadView];
    };
    [self registObservation:storageObservation];
    
    GCBaseObservationModel *observation1 = [GCBaseObservationModel new];
    observation1.observation = self.userViewModel;
    observation1.keyPath = @"companyBaseModel";
    observation1.handler = ^(NSString *keyPath) {
        [selfp reloadView];
    };
    [self registObservation:observation];
    [self registObservation:observation1];

}
-(void)reloadView
{
    [self.baseTable reloadData];
    [self.headView layoutSubviews];
    NSLog(@"======%@",[[GYStorageUserViewModel shareInterface] storageUserInfoModel].mobile);
    if (self.userViewModel.userPhone.length > 0||self.StorageUserViewModel.storageUserInfoModel.mobile.length>0) {
        @WeakSelf;
        [self setRightBarButtonWithTitle:@"退出登录" titleColor:[UIColor whiteColor] withBlock:^() {
            [[GYLoginViewModel shareInterface]requsetLogout];
            dispatch_async(dispatch_get_main_queue(), ^{
                [selfp setRightBarButtonWithTitle:@"" titleColor:[UIColor whiteColor] withBlock:NULL];
                [selfp.headView layoutSubviews];
            });
        }];
    }
}
-(void)reloadData
{
    switch (self.LoginViewModel.roleType) {
        case 1:
            [self.userViewModel requestUserInfo];
            break;
        case 2:
            [self.StorageUserViewModel requestUserShopBaseInfo];
            break;
        case 3:
            [self.StorageUserViewModel requestUserShopBaseInfo];
            break;
            
        default:
            break;
    }
    
}
///处理cellmodel事件
-(void)dealCellModel:(GYUserImageTitleCellModel *)model
{
    if (![[GYLoginViewModel shareInterface] loginstatus]) {
        [[GCPresenter shareInterface]loadLogin];
        return;
    }
    NSString *action = model.actionName;
    if ([action isEqualToString:@"callService"]) {
        NSString *msg = @"400-156-1517\n工作时间:周一至周五 9:00-17:30";
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"联系客服" message:msg preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[GCPresenter shareInterface] phoneCall:@"4001561517"];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        
        NSString *first = [action substringWithRange:NSMakeRange(0, 1)];
        action = [action stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[first uppercaseString]];
        NSString *vcclass = [NSString stringWithFormat:@"GYMine%@VC",action];
        
        if ([self.needAuths containsObject:action]) {
            
            if (self.LoginViewModel.roleType==1)
            {
                if (1 == self.userViewModel.userModel.logintype) {
                    [FTIndicator showToastMessage:@"您还没有通过认证！请先完成认证！"];
                    return;
                }
            }else
            {
                if (2 == [self.StorageUserViewModel.userCompanyAuthoStatus integerValue]) {
                    [FTIndicator showToastMessage:@"您的账号存在异常,请联系客服！"];
                    return;
                }
                if (3 == [self.StorageUserViewModel.userCompanyAuthoStatus integerValue]) {
                    [FTIndicator showErrorWithMessage:@"您提交的认证申请正在审核中,请耐心等待"];
                    return;
                }
                if (4 == [self.StorageUserViewModel.userCompanyAuthoStatus integerValue]) {
                    [FTIndicator showErrorWithMessage:@"您提交的认证申请被拒绝!"];
                    return;
                }
            }
            
        }
        
        Class class = NSClassFromString(vcclass);
        UIViewController *vc = [[class alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - life
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initilization];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.baseTable.frame = self.view.bounds;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.headView layoutSubviews];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - delegate
#pragma mark - scroll delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.headBGView.height = 0  > scrollView.contentOffset.y ? -scrollView.contentOffset.y : self.topShelterHeight;
}
#pragma mark - table delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSArray *sections = (1 == self.LoginViewModel.roleType ? self.userViewModel.userDetails : self.StorageUserViewModel.userDetails);
    return sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    GYTableSectionViewModel *sectionDic = (1 == self.LoginViewModel.roleType ? self.userViewModel.userDetails[section] : self.StorageUserViewModel.userDetails[section]);
    NSArray *items = (0 == _laytoutType ? (sectionDic.isHiden ? @[] : sectionDic.items) : @[@{}]);
    return items.count;
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return WFCGFloatY(45);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    CGFloat height = cell.height;
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellID = @"GYMineVCCellID";
    GYTableSectionViewModel *sectionDic = (1 == self.LoginViewModel.roleType ? self.userViewModel.userDetails[indexPath.section] : self.StorageUserViewModel.userDetails[indexPath.section]);
    GYMineCollectCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (cell == nil) {
        cell = [[GYMineCollectCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.model = sectionDic;
    @WeakSelf
    [cell setCallback:^(GYUserImageTitleCellModel *model) {
        [selfp dealCellModel:model];
    }];
    return cell;
}
///section header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    __block GYTableSectionViewModel *sectionDic = (1 == self.LoginViewModel.roleType ? self.userViewModel.userDetails[section] : self.StorageUserViewModel.userDetails[section]);
    
    UIView *headerV = [[UIView alloc] init];
    headerV.frame = CGRectMake(0, 0, self.view.width, WFCGFloatY(45));
    headerV.backgroundColor = [UIColor whiteColor];
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = Main_Color_White;
    
    UILabel *lab = [[UILabel alloc] init];
    lab.frame = CGRectMake(WFCGFloatX(15), 0, headerV.width - WFCGFloatX(15), headerV.height);
    lab.font = SYSTEMBOLDFONT(15);
    lab.textColor = Main_Color_Black;
    lab.userInteractionEnabled = YES;
    lab.text = sectionDic.sectionTitle;
    [headerV addSubview:lab];
    0 != _laytoutType ?: [WFFunctions WFUIaddBorderToView:headerV top:YES left:NO bottom:YES right:NO borderColor:Main_Color_BG borderWidth:0.5f];
    if (0 != _laytoutType) return headerV;
    
    @WeakSelf;
    [lab addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
        sectionDic.isHiden = !sectionDic.isHiden;
        if (1 == selfp.LoginViewModel.roleType)
        {
            [selfp.userViewModel.userDetails replaceObjectAtIndex:section withObject:sectionDic];
        }else
        {
            [selfp.StorageUserViewModel.userDetails replaceObjectAtIndex:section withObject:sectionDic];
        }
        [selfp.baseTable reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
    }];
    
    UIImageView* markIV = [[UIImageView alloc] init];
    markIV.image = [UIImage imageNamed:@"Shape"];
    markIV.width = WFCGFloatX(markIV.image.size.width);
    markIV.height = WFCGFloatY(markIV.image.size.height);
    markIV.x = self.view.width - WFCGFloatX(13) - markIV.width;
    markIV.centerY = headerV.height / 2;
    [headerV addSubview:markIV];
    
    CGAffineTransform transform = CGAffineTransformMakeRotation(sectionDic.isHiden ? 0 : M_PI / 2);
    [markIV setTransform:transform];
    
    return headerV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return WFCGFloatY(45);
}

///section footer
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [UIView new];
    view.backgroundColor = Main_Color_BG;
    if (0 != _laytoutType) {
        view.width = self.view.width;
        view.height = WFCGFloatY(5);
    }
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0 == _laytoutType ? 0.01f : WFCGFloatY(5);
}

-(void)tableView:(UITableView* )tableView willDisplayCell:(UITableViewCell* )cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setSeparatorInset:UIEdgeInsetsMake(0, WFCGFloatX(49), 0, 0)];
    [cell setLayoutMargins:UIEdgeInsetsZero];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([[GYLoginViewModel shareInterface] loginstatus]) {
        GYTableSectionViewModel *sectionDic = (1 == self.LoginViewModel.roleType ? self.userViewModel.userDetails[indexPath.section] : self.StorageUserViewModel.userDetails[indexPath.section]);
        NSArray *items = sectionDic.items;
        GYUserImageTitleCellModel *model = items[indexPath.row];
        [self dealCellModel:model];
    }else{
        [[GCPresenter shareInterface]loadLogin];
    }
}
@end


/*
 11111111111111111111111111111111111111001111111111111111111111111
 11111111111111111111111111111111111100011111111111111111111111111
 11111111111111111111111111111111100001111111111111111111111111111
 11111111111111111111111111111110000111111111111111111111111111111
 11111111111111111111111111111000000111111111111111111111111111111
 11111111111111111111111111100000011110001100000000000000011111111
 11111111111111111100000000000000000000000000000000011111111111111
 11111111111111110111000000000000000000000000000011111111111111111
 11111111111111111111111000000000000000000000000000000000111111111
 11111111111111111110000000000000000000000000000000111111111111111
 11111111111111111100011100000000000000000000000000000111111111111
 11111111111111100000110000000000011000000000000000000011111111111
 11111111111111000000000000000100111100000000000001100000111111111
 11111111110000000000000000001110111110000000000000111000011111111
 11111111000000000000000000011111111100000000000000011110001111111
 11111110000000011111111111111111111100000000000000001111100111111
 11111111000001111111111111111111110000000000000000001111111111111
 11111111110111111111111111111100000000000000000000000111111111111
 11111111111111110000000000000000000000000000000000000111111111111
 11111111111111111100000000000000000000000000001100000111111111111
 11111111111111000000000000000000000000000000111100000111111111111
 11111111111000000000000000000000000000000001111110000111111111111
 11111111100000000000000000000000000000001111111110000111111111111
 11111110000000000000000000000000000000111111111110000111111111111
 11111100000000000000000001110000001111111111111110001111111111111
 11111000000000000000011111111111111111111111111110011111111111111
 11110000000000000001111111111111111100111111111111111111111111111
 11100000000000000011111111111111111111100001111111111111111111111
 11100000000001000111111111111111111111111000001111111111111111111
 11000000000001100111111111111111111111111110000000111111111111111
 11000000000000111011111111111100011111000011100000001111111111111
 11000000000000011111111111111111000111110000000000000011111111111
 11000000000000000011111111111111000000000000000000000000111111111
 11001000000000000000001111111110000000000000000000000000001111111
 11100110000000000001111111110000000000000000111000000000000111111
 11110110000000000000000000000000000000000111111111110000000011111
 11111110000000000000000000000000000000001111111111111100000001111
 11111110000010000000000000000001100000000111011111111110000001111
 11111111000111110000000000000111110000000000111111111110110000111
 11111110001111111100010000000001111100000111111111111111110000111
 11111110001111111111111110000000111111100000000111111111111000111
 11111111001111111111111111111000000111111111111111111111111100011
 11111111101111111111111111111110000111111111111111111111111001111
 11111111111111111111111111111110001111111111111111111111100111111
 11111111111111111111111111111111001111111111111111111111001111111
 11111111111111111111111111111111100111111111111111111111111111111
 11111111111111111111111111111111110111111111111111111111111111111
 
 
 */
